<template>
  <div style="text-align: right; padding-top: 20px">
    <el-dropdown trigger="click" style="cursor: pointer">
      <div>
        <el-icon :size="size" style="margin: 12px 17px 0 0">
          <more />
        </el-icon>
      </div>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item icon="el-icon-user">
            <span>{{ username }}</span>
          </el-dropdown-item>
          <el-dropdown-item icon="el-icon-refresh" divided @click="refresh">
            <span>刷新</span>
          </el-dropdown-item>
          <el-dropdown-item icon="el-icon-close" divided @click="logout">
            <span>退出登录</span>
          </el-dropdown-item>
          <el-dropdown-item
            icon="el-icon-setting"
            divided
            @click="showVersionInfo"
          >
            <span>历史版本</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>

  <el-dialog title="历史版本" v-model="dialogVisible" width="80%">
    <timeline />
  </el-dialog>

  <div class="main">
    <div>
      <div style="font-weight: bold; margin-bottom: 30px; font-size: 20px">
        相关信息
      </div>
      <div style="line-height: 45px; font-size: 16px">
        <div>
          <label class="main-descriptions-label">寝室号：</label>
          <span>{{ room_number }}</span>
        </div>
        <div>
          <label class="main-descriptions-label">门状态：</label>
          <el-tag size="medium" :type="parseInt(door_status) ? 'success' : ''">
            {{ parseInt(door_status) ? '已开门' : '已关门' }}
          </el-tag>
        </div>
      </div>
    </div>

    <div style="text-align: center; margin-top: 150px">
      <div class="main-button">
        <el-button
          v-waves
          type="success"
          size="medium"
          @click="channgeRoomStatus('open')"
        >
          开门
        </el-button>
      </div>
      <div class="main-button">
        <el-button
          v-waves
          type="primary"
          size="medium"
          @click="channgeRoomStatus('close')"
        >
          关门
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { useStore } from 'vuex'
import { inject, reactive, toRefs, onBeforeMount } from 'vue'
import { More } from '@element-plus/icons'
import { updateRoomStatus } from '@/api/room'
import { ElMessage, ElMessageBox } from 'element-plus'
import { _throttle } from '@/utils/throttle'
import timeline from './components/timeline.vue'
import { BMapInit, getCurPosition, getDistance } from '@/utils/BMap'
import { getInfo } from '@/api/user'
import { isEmpty } from '@/utils/isEmpty'

export default {
  components: {
    More,
    timeline
  },
  setup() {
    const store = useStore()
    const reload = inject('reload')
    const data = reactive({
      size: 24,
      username: '',
      room_number: '',
      door_status: '',
      dialogVisible: false,
      BMap: null
    })

    const { username, room_number, door_status, dialogVisible, BMap } =
      toRefs(data)

    onBeforeMount(async () => {
      getUserInfo()
      BMap.value = await BMapInit()
    })

    const channgeRoomStatus = _throttle(async (status) => {
      const data = {}
      data.door_status = status == 'open' ? 1 : 0
      try {
        const res = await getInfo()
        // console.log(res)
        if (res.user_info.door_status == data.door_status) {
          ElMessage({
            message:
              '请勿重复' +
              (parseInt(res.user_info.door_status) ? '开门' : '关门'),
            type: 'error',
            duration: 2000
          })
          getUserInfo()
        } else {
          if (status == 'open') {
            const position = JSON.parse(res.user_info.room_position)
            let CurPosition = {
              lat: 0,
              lon: 0
            }
            if (isEmpty(BMap.value)) {
              CurPosition = position
            } else {
              CurPosition = await getCurPosition(BMap.value)
            }
            const distance = getDistance(
              CurPosition.lat,
              CurPosition.lon,
              position.lat,
              position.lon
            )
            // alert(distance)
            if (distance > 0.01) {
              ElMessageBox.confirm('距离超过10m，是否确定开门', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              })
                .then(async () => {
                  await changeDoorStatus(data)
                })
                .catch(() => {})
            } else {
              await changeDoorStatus(data)
            }
          } else if (status == 'close') {
            await changeDoorStatus(data)
          }
        }
      } catch (e) {
        window.console.log(e)
        // alert(e)
        const msg = status == 'open' ? '开门失败！' + e : '关门失败！' + e
        ElMessage({
          message: msg,
          type: 'error',
          duration: 2000
        })
      }
    }, 200)

    const changeDoorStatus = async (data) => {
      console.log(data)
      const res = await updateRoomStatus(data)
      console.log(res)
      if (res.code == 200) {
        door_status.value = res.data.door_status
        const msg = parseInt(res.data.door_status) ? '开门成功！' : '关门成功！'
        ElMessage({
          message: msg,
          type: 'success',
          duration: 2000
        })
      } else {
        ElMessage({
          message: res.msg,
          type: 'error',
          duration: 2000
        })
      }
    }

    const getUserInfo = async () => {
      const user_info = await store.dispatch('user/getInfo')
      username.value = user_info.username
      room_number.value = parseInt(user_info.room_number)
      door_status.value = parseInt(user_info.door_status)
    }

    const refresh = _throttle(async () => {
      await getUserInfo()
      reload()
    }, 200)

    const logout = _throttle(() => {
      store.dispatch('user/logout')
    }, 200)

    const showVersionInfo = () => {
      dialogVisible.value = true
    }

    return {
      ...toRefs(data),
      logout,
      refresh,
      channgeRoomStatus,
      showVersionInfo
    }
  }
}
</script>

<style lang="scss" scoped>
.main {
  display: inline-block;
  width: auto;
  position: relative;
  left: 50%;
  transform: translateX(-50%);
  margin-top: 100px;

  &-descriptions-label {
    margin-right: 10px;
  }

  &-button {
    margin: 40px 0;
  }
}

:deep(.el-descriptions__table > tbody > tr > td) {
  width: 100%;
}
:deep(.el-button) {
  width: 100%;
  height: 3.5em;
}
</style>
